#include <iostream>
#include <string>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>
using namespace std;

const int num = 5;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *running(void *attr)
{
    string name = static_cast<const char *>(attr);
    while(true)
    {
        pthread_mutex_lock(&mutex); //加锁
        // 添加到条件变量
        pthread_cond_wait(&cond, &mutex);
        cout << name << " IS RUNNING." << endl;
        pthread_mutex_unlock(&mutex); // 解锁
    }
}

int main()
{
    pthread_t tids[num];
    for (int i = 0; i < num; ++i)
    {
        char *thread_name = new char[32];
        snprintf(thread_name, 32, "thread_%d", i + 1);
        pthread_create(tids + i, nullptr, running, thread_name);
    }

    sleep(5);

    while(true)
    {
        pthread_cond_signal(&cond);
        sleep(1);
    }

    for (int i = 0; i < num; ++i)
        pthread_join(tids[i], nullptr);
    return 0;
}